﻿package com.designoutput.ui.newControls
{
    import com.designoutput.enum.Direction;
    import com.designoutput.event.ScrollEvent;
    import com.designoutput.icon.*;
    
    import flash.display.*;
    import flash.events.*;
    import flash.geom.*;

    public class VScroller extends ControlBase
    {
        private var _holder:Sprite;
		private var _content:DisplayObject;
		private var _scrollbar:Scrollbar;
		
		override protected function initialize():void {
			_holder = new Sprite();
			_holder.scrollRect = new Rectangle();
			addChild(_holder);
			
			_scrollbar = new Scrollbar(Direction.Vertical);
			addChild(_scrollbar);
			
			_holder.addEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelHandler, false, 0, true);
			_scrollbar.addEventListener(ScrollEvent.SCROLL, scrollHandler);
		}
		
		public function setContent(content:DisplayObject):void {
			if(_content != null){
				_holder.removeChild(_content);
				_content = null;
			}
			
			_content = content;
			
			if(_content != null){
				_holder.addChild(_content);
			}
		}
		
		override protected function updateDisplay():void {
			super.updateDisplay();
			
			var rect:Rectangle = _holder.scrollRect;
			rect.width = _width;
			rect.height = _height;
			_holder.scrollRect = rect;
			
			_scrollbar.x = _width - 16;
			
			_scrollbar.size = _height;
			_scrollbar.contentSize = _content.height;
			_scrollbar.viewportSize = _height;
			
			_scrollbar.visible = _scrollbar.contentSize > _scrollbar.viewportSize;
		}
		
		private function scrollHandler(e:ScrollEvent):void {
			var rect:Rectangle = _holder.scrollRect || new Rectangle();
			rect.y = _scrollbar.scrollAmount;			
			_holder.scrollRect = rect;	
		}
		
        private function mouseWheelHandler(evt:MouseEvent) : void
        {
			_scrollbar.scrollAmount -= evt.delta * 3;
        }
		
		public function updateContentSize():void {
			invalidateDisplay();
		}
    }
}
